package com.ruoyi.project.business.controlcenter.iot.config;

import com.ruoyi.project.business.controlcenter.iot.mqtt.TopicUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
// TODO 用 Configuration?
public class MqttTopicConfig implements InitializingBean {

    @Resource
    private MqttPahoMessageDrivenChannelAdapter messageProducer;

    public List<String> findAllRuningTopic(Long tenantId) {
        String[] topics = messageProducer.getTopic();
        List<String> collect = Arrays.stream(topics).filter(topic -> StringUtils.endsWith(topic, "_" + tenantId)).collect(Collectors.toList());
        return collect;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
//        List<DeviceDTO> list = deviceService.findAllGatewayDevice();
        List<Long> tenantIds = Arrays.asList(1L);
        for(Long tenantId : tenantIds) {
            log.info("启动初始化 topic: {}", tenantId);
            String mqttTopic = TopicUtil.genGatewayPubTopic(tenantId);
            log.info("启动初始化 topic: {}", mqttTopic);
            Integer qos = 1;
            if(qos == null) {
                qos = 1;
            }
            try {
                messageProducer.addTopic(mqttTopic, qos);
            } catch (Exception e) {
                log.warn("afterPropertiesSet 添加 topic 异常: {}", e.getMessage());
            }
        }
    }

}
